package cn.zhqr.core.interceptor;

import cn.zhqr.common.annotations.HasAllPerm;
import cn.zhqr.common.annotations.HasAllRole;
import cn.zhqr.common.annotations.HasAnyPerm;
import cn.zhqr.common.annotations.HasAnyRole;
import cn.zhqr.common.utils.PermKit;
import cn.zhqr.core.controller.base.BaseController;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import org.apache.log4j.Logger;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 *  权限拦截器
 * Created by charles on 2018/6/20.
 */
public class PermInterceptor implements Interceptor{
    private static Logger log = Logger.getLogger(PermInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        if(inv.getController() instanceof BaseController){
            BaseController controller = (BaseController) inv.getController();
            Annotation[] class_annotations = inv.getController().getClass().getAnnotations();
            Annotation[] method_annotations = inv.getMethod().getAnnotations();

            List<Annotation> all_annotations = new ArrayList<>();
            all_annotations.addAll(Arrays.asList(class_annotations));
            all_annotations.addAll(Arrays.asList(method_annotations));

            for(Annotation annotation : all_annotations){
                if(annotation instanceof HasAnyPerm){
                    PermKit.hasAnyPerm(controller.getUserInfo(), ((HasAnyPerm)annotation).value());
                }else if(annotation instanceof HasAllPerm){
                    PermKit.hasAllPerm(controller.getUserInfo(), ((HasAllPerm)annotation).value());
                }else if(annotation instanceof HasAnyRole){
                    PermKit.hasAnyRole(controller.getUserInfo(), ((HasAnyRole)annotation).value());
                }else if(annotation instanceof HasAllRole){
                    PermKit.hasAllRole(controller.getUserInfo(), ((HasAllRole)annotation).value());
                }
            }
        }
        inv.invoke();
    }
}
